﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
using WP7Panels;

using LocalDatabaseSample.Model;
using LocalDatabaseSample.ViewModel;

namespace DemoShoppingList
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }
                
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (NavigationContext.QueryString.ContainsKey("text"))
            {
                string newListName = NavigationContext.QueryString["text"].ToString();
                ShoppingList newList = new ShoppingList { ListName = newListName };
                App.ViewModel.AddNewShoppingList(newList);
                NavigationService.RemoveBackEntry();
                pivot.UpdateLayout();
            }
            if (NavigationContext.QueryString.ContainsKey("back"))
            {
                NavigationService.RemoveBackEntry();
            }
        }
        
        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }

            if (App.ViewModel.ShoppingLists.Count != 0)
            {
                RedrawPivot();
            }
            else
            {
                //Add an empty list
            }
        }

        private void ApplicationBarIconButton_About(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/LiveSignIn.xaml", UriKind.Relative));
        }

        private void ApplicationBarIconButton_Add(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/AddPage.xaml", UriKind.Relative));            
        }

        private void ApplicationBarIconButton_Del(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you really want to delete the selected list?", "Question", MessageBoxButton.OKCancel)
                == MessageBoxResult.OK)
            {
                PivotItem curItem = (PivotItem)pivot.SelectedItem;
                if (curItem != null)
                {
                    ShoppingList delList = (ShoppingList)curItem.Tag;
                    App.ViewModel.DeleteShoppingList(delList);
                }
                MessageBox.Show("List was deleted succefully", "Deleted", MessageBoxButton.OK);
                RedrawPivot();
            }
        }

        private void button1_AddElement(object sender, RoutedEventArgs e)
        {
            PivotItem curItem = (PivotItem)pivot.SelectedItem;
            if (curItem != null)
            {
                ShoppingList curList = (ShoppingList)curItem.Tag;
                App.ViewModel.AddNewShoppingListElement(curList,
                    new ShoppingListElement
                    {
                        ListId = curList.ListId,
                        Name = textBox1.Text,
                        IsComplete = false,
                        Note = textBox1.Text + " Note"
                    });
                RedrawPivot();
            }
            else
            {
                MessageBox.Show("Please, create list at first!", "Information", MessageBoxButton.OK);
            }
            textBox1.Text = "";
        }

        private void RedrawPivot()
        {
            pivot.Items.Clear();
            foreach (LocalDatabaseSample.Model.ShoppingList sList in App.ViewModel.ShoppingLists)
            {                
                PivotItem newPivotItem = new PivotItem();
                newPivotItem.Header = sList.ListName;

                StackPanel panel = new StackPanel();
                
                foreach (LocalDatabaseSample.Model.ShoppingListElement lElement in sList.listElements)
                {
                    DockPanel stackPanel = new DockPanel();
                    
                    TextBlock newTb = new TextBlock();
                    newTb.Text = lElement.Note;
                    newTb.TextAlignment = TextAlignment.Left;
                    newTb.TextWrapping = TextWrapping.Wrap;
                    newTb.SetValue(DockPanel.DockProperty, Dock.Bottom);

                    stackPanel.Children.Add(newTb);

                    Image newImage = new Image();
                    newImage.Source = new BitmapImage(new Uri("/Images/appbar.delete.rest.png", UriKind.Relative));
                    newImage.Width = 60;
                    newImage.Height = 60;
                    newImage.SetValue(DockPanel.DockProperty, Dock.Right);
                    newImage.Tag = lElement;
                    newImage.MouseLeftButtonUp += new MouseButtonEventHandler(newImage_MouseLeftButtonUp);

                    stackPanel.Children.Add(newImage);
                    
                    CheckBox newCh = new CheckBox();
                    newCh.Content = lElement.Name;
                    newCh.IsChecked = lElement.IsComplete;
                    newCh.FontStyle = FontStyles.Normal;
                    newCh.FontSize = 36;
                    newCh.FontFamily = new System.Windows.Media.FontFamily("Segoe WP SemiLight");
                    newCh.Tag = lElement;
                    newCh.Checked += new RoutedEventHandler(newCh_Checked);
                    newCh.Unchecked += new RoutedEventHandler(newCh_Unchecked);
                    newCh.SetValue(DockPanel.DockProperty, Dock.Left);
                    
                    stackPanel.Children.Add(newCh);
                                                      
                    panel.Children.Add(stackPanel);
                }

                newPivotItem.Content = panel;
                newPivotItem.Tag = sList;
                pivot.Items.Add(newPivotItem);
            }
        }

        void newCh_Unchecked(object sender, RoutedEventArgs e)
        {
            PivotItem curItem = (PivotItem)pivot.SelectedItem;
            ShoppingList curList = (ShoppingList)curItem.Tag;

            CheckBox chCheck = (CheckBox)sender;
            ShoppingListElement chElement = (ShoppingListElement)chCheck.Tag;
            App.ViewModel.SubmitChecking(curList, chElement, false);
        }

        void newCh_Checked(object sender, RoutedEventArgs e)
        {
            PivotItem curItem = (PivotItem)pivot.SelectedItem;
            ShoppingList curList = (ShoppingList)curItem.Tag;

            CheckBox chCheck = (CheckBox)sender;
            ShoppingListElement chElement = (ShoppingListElement)chCheck.Tag;
            App.ViewModel.SubmitChecking(curList, chElement, true);
        }

        void newImage_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            PivotItem curItem = (PivotItem)pivot.SelectedItem;
            ShoppingList curList = (ShoppingList) curItem.Tag;

            Image delImage = (Image)sender;
            ShoppingListElement delElement = (ShoppingListElement)delImage.Tag;
            App.ViewModel.DeleteShoppingListElement(curList, delElement);

            RedrawPivot();
        }

        private void ApplicationBarMenuItem_SkyDrive(object sender, EventArgs e)
        {            
            PivotItem curItem = (PivotItem)pivot.SelectedItem;
            ShoppingList curList = (ShoppingList)curItem.Tag;
            String strBody = "";

            foreach (ShoppingListElement elem in curList.listElements)
            {
                strBody += "[" + Convert.ToInt32(elem.IsComplete) + "] " +
                    elem.Name + " Note:" + elem.Note + "\n";
            }
            
            NavigationService.Navigate(new Uri("/LiveSignIn.xaml?body=" + strBody
                + "&fileName=" + curList.ListName, UriKind.Relative));
        }

        private void ApplicationBarMenuItem_About(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/AboutPage.xaml", UriKind.Relative));
        }

        private void ApplicationBarIconButton_SMS(object sender, EventArgs e)
        {
            SmsComposeTask smsTask = new SmsComposeTask();

            PivotItem curItem = (PivotItem)pivot.SelectedItem;
            ShoppingList curList = (ShoppingList) curItem.Tag;

            smsTask.Body = curList.ListName + "\n";

            foreach (ShoppingListElement elem in curList.listElements)
            {
                smsTask.Body += "[" + Convert.ToInt32(elem.IsComplete) + "] " +
                    elem.Name + " Note:" + elem.Note + "\n";
            }
            smsTask.Show();
        }

        private void ApplicationBarIconButton_mail(object sender, EventArgs e)
        {
            EmailComposeTask emailTask = new EmailComposeTask();

            PivotItem curItem = (PivotItem)pivot.SelectedItem;
            ShoppingList curList = (ShoppingList)curItem.Tag;

            emailTask.Body = curList.ListName + "\n";

            foreach (ShoppingListElement elem in curList.listElements)
            {
                emailTask.Body += "[" + Convert.ToInt32(elem.IsComplete) + "] " +
                    elem.Name + " Note:" + elem.Note + "\n";
            }
            emailTask.Show();
        }
    }
}